import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { FaFilter, FaCalendarAlt, FaSync } from 'react-icons/fa';
import '../styles/ChangelogList.css';

const ChangelogList = () => {
  const [changelogs, setChangelogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [sources, setSources] = useState([]);
  const [organizations, setOrganizations] = useState([]);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  });
  
  // 筛选条件
  const [filters, setFilters] = useState({
    sourceId: '',
    changeType: '',
    startDate: '',
    endDate: '',
    organization: ''
  });

  // 获取变更日志列表
  const fetchChangelogs = async (page = 1) => {
    try {
      setLoading(true);
      
      const params = {
        page,
        limit: pagination.limit,
        ...filters
      };
      
      const res = await axios.get('/api/changelog', { params });
      setChangelogs(res.data.changelogs);
      setPagination(res.data.pagination);
      setError(null);
    } catch (err) {
      console.error('获取变更日志列表失败:', err);
      setError('获取变更日志列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 获取采集源列表
  const fetchSources = async () => {
    try {
      const res = await axios.get('/api/sources');
      setSources(res.data);
      
      // 提取不重复的组织列表
      const orgs = [...new Set(res.data.map(source => source.organization))];
      setOrganizations(orgs);
    } catch (err) {
      console.error('获取采集源列表失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchChangelogs();
    fetchSources();
  }, []);

  // 筛选条件变化时重新加载
  useEffect(() => {
    fetchChangelogs(1);
  }, [filters]);

  // 处理筛选条件变化
  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prev => ({ ...prev, [name]: value }));
    
    // 如果选择了组织，则清空具体采集源
    if (name === 'organization' && value) {
      setFilters(prev => ({ ...prev, sourceId: '', [name]: value }));
    }
  };

  // 重置筛选条件
  const handleResetFilters = () => {
    setFilters({
      sourceId: '',
      changeType: '',
      startDate: '',
      endDate: '',
      organization: ''
    });
  };

  // 处理分页
  const handlePageChange = (newPage) => {
    if (newPage < 1 || newPage > pagination.pages) return;
    fetchChangelogs(newPage);
  };

  // 格式化变更类型
  const formatChangeType = (type) => {
    const typeMap = {
      'new': '新增',
      'updated': '更新',
      'removed': '移除'
    };
    
    return typeMap[type] || type;
  };

  // 获取筛选后的采集源列表
  const filteredSources = filters.organization 
    ? sources.filter(source => source.organization === filters.organization) 
    : sources;

  return (
    <div className="changelog-list-container">
      <div className="page-header">
        <h1>变更日志</h1>
        <button 
          onClick={() => fetchChangelogs(pagination.page)} 
          className="refresh-button"
          title="刷新"
        >
          <FaSync />
        </button>
      </div>

      {error && <div className="error-message">{error}</div>}

      {/* 筛选器 */}
      <div className="filters">
        <div className="filter-options">
          <div className="filter-group">
            <label>组织:</label>
            <select
              name="organization"
              value={filters.organization}
              onChange={handleFilterChange}
            >
              <option value="">所有组织</option>
              {organizations.map(org => (
                <option key={org} value={org}>{org}</option>
              ))}
            </select>
          </div>

          <div className="filter-group">
            <label>采集源:</label>
            <select
              name="sourceId"
              value={filters.sourceId}
              onChange={handleFilterChange}
              disabled={!filteredSources.length}
            >
              <option value="">所有采集源</option>
              {filteredSources.map(source => (
                <option key={source._id} value={source._id}>
                  {source.name}
                </option>
              ))}
            </select>
          </div>

          <div className="filter-group">
            <label>变更类型:</label>
            <select
              name="changeType"
              value={filters.changeType}
              onChange={handleFilterChange}
            >
              <option value="">所有类型</option>
              <option value="new">新增</option>
              <option value="updated">更新</option>
              <option value="removed">移除</option>
            </select>
          </div>
        </div>

        <div className="date-filters">
          <div className="filter-group">
            <label>开始日期:</label>
            <div className="date-input-container">
              <FaCalendarAlt className="calendar-icon" />
              <input
                type="date"
                name="startDate"
                value={filters.startDate}
                onChange={handleFilterChange}
              />
            </div>
          </div>

          <div className="filter-group">
            <label>结束日期:</label>
            <div className="date-input-container">
              <FaCalendarAlt className="calendar-icon" />
              <input
                type="date"
                name="endDate"
                value={filters.endDate}
                onChange={handleFilterChange}
              />
            </div>
          </div>

          <button 
            onClick={handleResetFilters} 
            className="reset-button"
          >
            重置筛选
          </button>
        </div>
      </div>

      {/* 变更日志列表 */}
      {loading && changelogs.length === 0 ? (
        <div className="loading">加载中...</div>
      ) : changelogs.length > 0 ? (
        <div className="changelog-table-container">
          <table className="changelog-table">
            <thead>
              <tr>
                <th>人员</th>
                <th>组织</th>
                <th>变更类型</th>
                <th>时间</th>
                <th>详细变更</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {changelogs.map(log => (
                <tr key={log._id}>
                  <td>
                    {log.personnelId ? (
                      <Link to={`/personnel/${log.personnelId._id}`}>
                        {log.personnelId.name}
                      </Link>
                    ) : '未知'}
                  </td>
                  <td>{log.personnelId?.organization || log.sourceId?.organization || '未知'}</td>
                  <td>
                    <span className={`status status-${log.changeType === 'new' ? 'active' : 
                                                log.changeType === 'updated' ? 'changed' : 
                                                'inactive'}`}>
                      {formatChangeType(log.changeType)}
                    </span>
                  </td>
                  <td>{new Date(log.timestamp).toLocaleString()}</td>
                  <td>
                    {log.changedFields && log.changedFields.length > 0 ? (
                      <span>{log.changedFields.length}个字段变更</span>
                    ) : (
                      <span className="log-details">{log.details || '无详细信息'}</span>
                    )}
                  </td>
                  <td>
                    <Link to={`/personnel/${log.personnelId?._id}`} className="view-button">
                      查看详情
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* 分页 */}
          {pagination.pages > 1 && (
            <div className="pagination">
              <button 
                onClick={() => handlePageChange(1)} 
                disabled={pagination.page === 1}
                className="page-button"
              >
                首页
              </button>
              <button 
                onClick={() => handlePageChange(pagination.page - 1)} 
                disabled={pagination.page === 1}
                className="page-button"
              >
                上一页
              </button>
              <span className="page-info">
                {pagination.page} / {pagination.pages}
              </span>
              <button 
                onClick={() => handlePageChange(pagination.page + 1)} 
                disabled={pagination.page === pagination.pages}
                className="page-button"
              >
                下一页
              </button>
              <button 
                onClick={() => handlePageChange(pagination.pages)} 
                disabled={pagination.page === pagination.pages}
                className="page-button"
              >
                末页
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="no-data">
          没有找到符合条件的变更日志
        </div>
      )}
    </div>
  );
};

export default ChangelogList; 